/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.config;

import cn.ac.nercis.pes.community.constant.AppConstants;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 应用配置
 *
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
@Configuration
public class AppConfig {
    @Getter
    @Value("${module.enable-operation-log}")
    private Boolean enableOperationLog;
    @Getter
    @Value("${module.display-name}")
    private String appTitle;
    @Getter
    @Value("${module.version}")
    private String appVersion;
    @Getter
    @Value("${module.copyright}")
    private String appCopyright;

    @Bean
    public static ExecutorService provideExecutorService() {
        final AtomicInteger threadNumber = new AtomicInteger(1);
        return new ThreadPoolExecutor(AppConstants.NUM_CORE_BG_THREADS,AppConstants.MAX_POOL_SIZE, AppConstants.BG_THREAD_KEEPALIVE_SECONDS,TimeUnit.SECONDS,new LinkedBlockingDeque<>(),r -> {
            String name = String.format("App Background Thread %03d", threadNumber.getAndIncrement());
            Thread t = new Thread(r);
            t.setName(name);
            t.setUncaughtExceptionHandler(AppConfig::handleUncaughtExceptionInBackgroundThread);
            t.setDaemon(true);
            log.debug("Starting {}", t.getName());
            return t;
        });
    }

    public static void handleUncaughtExceptionInBackgroundThread(Thread thread, Throwable throwable) {
        log.error("未捕获的异常" + thread.getName(), throwable);
    }

}